﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Thor.Common;


namespace Thor.Repository.Azure.Queue
{
    public abstract class QueueRepositoryBase : IRepository
    {
        #region Constants

        private const string QUEUEADDRESS = "QueueAddress";
        private const string CONNECTIONSTRING = "ConnectionString";

        #endregion

        #region Fields

        protected static CloudQueueClient _queueStorage;
        protected static bool _createdQueue = false;
        protected static object _lock = new Object();

        #endregion

        #region Constructors

        public QueueRepositoryBase(Dictionary<string, object> repositoryParameters)
        {
            RepositoryParameters = repositoryParameters;
        }

        #endregion

        #region Properties

        public CloudStorageAccount StorageAccount
        {
            get
            {
                if (RepositoryParameters[CONNECTIONSTRING] != null)
                    return CloudStorageAccount.FromConfigurationSetting(Convert.ToString(RepositoryParameters[CONNECTIONSTRING]));
                else
                    return null;
            }
        }

        public string QueueAddress
        {
            get
            {
                if (RepositoryParameters[QUEUEADDRESS] != null)
                    return Convert.ToString(RepositoryParameters[QUEUEADDRESS]);
                else
                    return string.Empty;
            }
            set
            {
                if (RepositoryParameters[QUEUEADDRESS] != null)
                    RepositoryParameters[QUEUEADDRESS] = value;
            }
        }

        #endregion

        #region Methods

        private void CreateQueue()
        {
            if (_createdQueue)
                return;

            lock (_lock)
            {
                if (_createdQueue)
                    return;

                _queueStorage = this.StorageAccount.CreateCloudQueueClient();
                CloudQueue queue = _queueStorage.GetQueueReference(this.QueueAddress);
                queue.CreateIfNotExist();

                _createdQueue = true;
            }
        }

        protected CloudQueue GetQueue()
        {
            CreateQueue();
            return _queueStorage.GetQueueReference(this.QueueAddress);
        }

        #endregion

        #region IRepository Members

        public Dictionary<string, object> RepositoryParameters { get; set; }

        #endregion
    }
}
